app.controller('VenueCtrl', [
    '$scope', 'alertService', 'venueService', '$modal',
    function ($scope, alertService, venueService, $modal) {
        venueService.getAllAsync(false)
            .then(function (result) {
                $scope.venueList = result;
            }, alertService.error);

        $scope.enable = function (venue) {
            venueService.enableAsync(venue.Id, venue.Enabled)
                .then(function () {
                    venue.Enabled = !venue.Enabled;
                }, alertService.error);
        }
    }
]);


app.controller('VenueEditCtrl', [
    '$scope', 'alertService', 'venueService', '$stateParams','$q','fileService',
    function ($scope, alertService, venueService, $stateParams,$q,fileService) {
        $scope.CoverImage = { file: undefined };
        $scope.FrontImage = { file: undefined };
        if ($stateParams.id > 0) {
            venueService.getAsync($stateParams.id)
                .then(function (result) {
                    $scope.venue = result;
                }, alertService.error);
        } else {
            $scope.venue = { Id: 0, Name: '新增场馆' };
        }

        $scope.submit = function () {
            $q.all([
                function() {
                    var defer1 = $q.defer();
                    fileService.upload($scope.CoverImage.file)
                        .then(function(url) {
                            if (url) $scope.venue.ImageUrl = url;
                            defer1.resolve();
                        }, function(x) {
                            defer1.reject(x);
                        });
                    return defer1.promise;
                }(),
                function() {
                    var defer2 = $q.defer();
                    fileService.upload($scope.FrontImage.file)
                        .then(function(url) {
                            if (url) $scope.venue.FrontImageUrl = url;
                            defer2.resolve();
                        }, function(x) {
                            defer2.reject(x);
                        });
                    return defer2.promise;
                }()]
            ).then(function() {
                    update();
                },
                alertService.error
            );
        };

        function update() {
            venueService.createOrUpdateAsync($scope.venue)
                .then(function (result) {
                    $scope.venue.Id = result;
                    alertService.success('提交成功');
                }, alertService.error);
        }
    }
]);

app.controller('VenueBookCtrl', [
    '$scope', 'alertService', 'venueService', '$stateParams','$modal',
    function ($scope, alertService, venueService, $stateParams, $modal) {
        $scope.venueId=$stateParams.id;
        var selectedMonth=0;
        venueService.getAsync($stateParams.id)
            .then(function (result) {
                $scope.venue = result;
            }, alertService.error);

        $scope.getBookedDays = function (month) {
            selectedMonth=month;
            getBookRecords(month);
            return venueService.getBookedDays(month, $stateParams.id);
        }

        function getBookRecords(month) {
            venueService.getBookRecords(month, $stateParams.id)
                .then(function (result) {
                    $scope.recordList = result;
                }, alertService.error);
        }

        $scope.audit = function (book) {
            var modelInstance = $modal.open({
                templateUrl: 'tpl/app-venue-book-audit.html',
                windowClass: 'response-modal',
                backdrop: false,
                controller: [
                    '$scope', 'venueService',
                    function (scope, venueService) {
                        scope.auditForm = { description: '', status: 1 };
                        scope.submit = function () {
                            if (scope.auditForm.status == 2 && scope.auditForm.description == '') {
                                alertService.add('请输入不通过的原因');
                                return;
                            }
                            venueService.auditAsync(book.Id, scope.auditForm.status, scope.auditForm.description)
                                .then(function (result) {
                                    book.Status = scope.auditForm.status;
                                    modelInstance.dismiss('ok');
                                }, alertService.error);
                        };

                        scope.miss = function () {
                            modelInstance.dismiss();
                        };
                    }
                ]
            });
        };

        $scope.book=function(){
             var modelInstance = $modal.open({
                templateUrl: 'tpl/app-venue-book-modal.html',
                windowClass: 'response-modal',
                backdrop: false,
                controller: [
                    '$scope',
                    function (scope) {
                        scope.venueId=$scope.venueId;
                        scope.miss = function () {
                            modelInstance.dismiss();
                            $scope.getBookedDays(selectedMonth);
                        };
                    }
                ]
            });
        }
    }
]);

app.factory('venueService', [
    '$http', '$q',
    function ($http, $q) {
        var self = {};

        self.getAllAsync = function (onlyEnabled) {
            var defer = $q.defer();
            var httpConfig = {
                url: '/api/Venue',
                params: { onlyEnabled: onlyEnabled }
            };
            $http(httpConfig).success(function (result) {
                if (result.Code >= 0) defer.resolve(result.Data);
                else defer.reject(result.Message);
            }).error(function (x) {
                defer.reject('查询列表失败，请稍后再试');
            });

            return defer.promise;
        };

        self.getAsync = function (id) {
            var defer = $q.defer();
            var httpConfig = {
                url: '/api/Venue',
                params: { id: id }
            };
            $http(httpConfig).success(function (result) {
                if (result.Code >= 0) defer.resolve(result.Data);
                else defer.reject(result.Message);
            }).error(function (x) {
                defer.reject('查询列表失败，请稍后再试');
            });

            return defer.promise;
        };

        self.enableAsync = function (id, enabled) {
            var defer = $q.defer();
            $http({
                url: '/api/Venue/' + (enabled ? 'Delete' : 'Resume'),
                method: 'POST',
                params: { id: id }
            }).success(function (result) {
                if (result.Code >= 0) defer.resolve(result.Data);
                else defer.reject(result.Message);
            }).error(function (x) {
                defer.reject('操作失败，请稍后再试');
            });

            return defer.promise;
        };

        self.createOrUpdateAsync = function (model) {
            var defer = $q.defer();
            $http({
                url: '/api/Venue/' + (model.Id > 0 ? 'Update' : 'Create'),
                method: 'POST',
                data: model
            }).success(function (result) {
                if (result.Code >= 0) defer.resolve(result.Code);
                else defer.reject(result.Message);
            }).error(function (x) {
                defer.reject('提交失败，请稍后再试');
            });

            return defer.promise;
        };

        self.getBookedDays = function (month, venueId) {
            var defer = $q.defer();
            $http({
                url: '/api/Venue/BookedDays',
                params: {
                    venueId: venueId,
                    month: month
                }
            }).success(function (result) {
                if (result.Code >= 0) {
                    defer.resolve(result.Data);
                } else {
                    defer.reject(result.Message);
                }
            }).error(function (x) {
                defer.reject('查询预定记录失败')
            });
            return defer.promise;
        };

        self.getBookRecords = function (month, venueId) {
            var defer = $q.defer();
            $http({
                url: '/api/Venue/BookRecord',
                params: {
                    venueId: venueId,
                    month: month
                }
            }).success(function (result) {
                if (result.Code >= 0) {
                    defer.resolve(result.Data);
                } else {
                    defer.reject(result.Message);
                }
            }).error(function (x) {
                defer.reject('查询预定记录失败');
            });
            return defer.promise;
        };


        self.auditAsync = function (enrollId, status, description) {
            var defer = $q.defer();
            $http({
                method: 'POST',
                url: '/api/Venue/Audit',
                params: {
                    enrollId: enrollId,
                    statusId: status,
                    description: description
                }
            }).success(function (result) {
                if (result.Code >= 0) defer.resolve(true);
                else defer.reject(result.Message);
            }).error(function (x) {
                defer.reject('提交审核失败，请稍后再试');
            });
            return defer.promise;
        };

        return self;
    }
]);

app.directive('clndr', function () {
    return {
        restrict: 'A',
        scope: {
            onMonthChange: '&'
        },
        link: function (scope, element, attrs) {
            var calendars = {};
            calendars.daysOfTheWeek = ['日', '一', '二', '三', '四', '五', '六'];

            calendars.template =
                "<div class='clndr-controls'>" +
                "<div class='clndr-control-button previous'>" +
                "<span class='clndr-previous-button'></span>" +
                "</div>" +
                "<div class='month'><%= year %>年<%= month %></div>" +
                "<div class='clndr-control-button next'>" +
                "<span class='clndr-next-button'></span>" +
                "</div>" +
                "<div class='help'><span class='all'></span>为可选时段 <span class='none'></span>为已占用时段 </div>" +
                "<hr/>" +
                "</div>" +
                "<table class='clndr-table' border='0' cellspacing='0' cellpadding='0'>" +
                "<thead>" +
                "<tr class='header-days'>" +
                "<% for(var i = 0; i < daysOfTheWeek.length; i++) { %>" +
                "<td class='header-day'><%= daysOfTheWeek[i] %></td>" +
                "<% } %>" +
                "</tr>" +
                "</thead>" +
                "<tbody>" +
                "<% for(var i = 0; i < numberOfRows; i++){ %>" +
                "<tr>" +
                "<% for(var j = 0; j < 7; j++){ %>" +
                "<% var d = j + i * 7; %>" +
                "<td class='<%= days[d].classes %>'>" +
                "<div class='day-contents'><%= days[d].day %></div>" +
                "</td>" +
                "<% } %>" +
                "</tr>" +
                "<% } %>" +
                "</tbody>" +
                "</table>";

            function handleMonthChange(month) {
                if (scope.onMonthChange) {
                    scope.onMonthChange()(month)
                        .then(function (result) {
                            var events = [];
                            result.BookDays.forEach(function (item) {
                                events.push({
                                    date: item.Day,
                                    data: item.BookType
                                });
                            });
                            scope.clndr1.setEvents(events);
                        });
                }
            }
            scope.clndr1 = $(element).clndr({
                daysOfTheWeek: calendars.daysOfTheWeek,
                template: calendars.template,
                // events: eventArray,
                clickEvents: {
                    click: function (target) {
                    },
                    today: function () {
                        console.log('Cal-1 today');
                    },
                    nextMonth: function () {
                        console.log('Cal-1 next month');
                    },
                    previousMonth: function () {
                        console.log('Cal-1 previous month');
                    },
                    onMonthChange: function (event) {
                         var month = parseInt(event.format('YYYYMM'));
                        handleMonthChange(month);
                    },
                    nextYear: function () {
                        console.log('Cal-1 next year');
                    },
                    previousYear: function () {
                        console.log('Cal-1 previous year');
                    },
                    onYearChange: function () {
                        console.log('Cal-1 year changed');
                    },
                    nextInterval: function () {
                        console.log('Cal-1 next interval');
                    },
                    previousInterval: function () {
                        console.log('Cal-1 previous interval');
                    },
                    onIntervalChange: function () {
                        console.log('Cal-1 interval changed');
                    }
                },
                multiDayEvents: {
                    singleDay: 'date',
                    endDate: 'endDate',
                    startDate: 'startDate'
                },
                showAdjacentMonths: false,
                adjacentDaysChangeMonth: false
            });

            setTimeout(function(){
                handleMonthChange(parseInt(moment().format('YYYYMM')));
            }, 100);
        }
    }
});